var e = (0, require("../../@babel/runtime/helpers/interopRequireDefault").default)(require("../../utils/mqtt.js")),
  t = getApp(),
  a = require("../../utils/util.js"),
  o = require("../../utils/aliIot-sdk.js"),
  n = require("../../utils/aliyun/hex_hmac_sha1"),
  c = require("../../utils/aliyun/aliyun_connect.js");
Page({
  data: {
    textLog: "",
    isopen: !1,
    devices: [],
    connected: !1,
    chs: [],
    inifile_path: "",
    fork_select_flag: !0,
    ManufacturerData_count: 0,
    mqtt_payload_msg: "",
    mqtt_conect_flag: !1,
    reconnectCounts: 0,
    options: {
      protocolVersion: 4,
      clean: !1,
      reconnectPeriod: 1e3,
      connectTimeout: 3e4,
      resubscribe: !0,
      clientId: "",
      password: "",
      username: ""
    },
    aliyunInfo: {
      productKey: "a1qEt2hbIqy",
      deviceName: "mcu_B",
      deviceSecret: "df945d33036ae2d482b723b6c07c2967",
      regionId: "cn-shanghai"
    }
  },
  onLoad: function (e) {
    var a = this;
    t.globalData.Storage_deviceId = wx.getStorageSync("deviceId"), o = wx.getStorageSync("fork_moden_select_flag"), console.log("fork_moden_select_flag:" + o), "true" == o ? (a.setData({
      fork_select_flag: !0
    }), t.globalData.fork_select_flag = !0) : (a.setData({
      fork_select_flag: !1
    }), t.globalData.fork_select_flag = !1), console.log("fork_moden_select_flag after:" + a.data.fork_select_flag), t.globalData.CAN_debug_mode = wx.getStorageSync("can_debug_mode"), t.globalData.wx_openid = wx.getStorageSync("wx_openid_key"), "" == t.globalData.wx_openid ? wx.cloud.callFunction({
      name: "quickstartFunctions",
      config: {
        env: this.data.envId
      },
      data: {
        type: "getOpenId"
      }
    }).then((function (e) {
      t.globalData.wx_openid = e.result.openid, console.log(e.result.openid), wx.setStorageSync("wx_openid_key", t.globalData.wx_openid), "" == t.globalData.Storage_deviceId && (t.globalData.auto_conect = !1), a.startScan()
    })).catch((function (e) {})) : ("" == t.globalData.Storage_deviceId && (t.globalData.auto_conect = !1), a.startScan());
    var o, n, c = "";
    if ("" != (o = wx.getStorageSync("mqtt_payload_msg")) && (c = JSON.parse(o)), "" != c && (n = c.deviceName), "" != c && t.globalData.wx_openid == n) a.conect_aliyun_mqtt(c);
    else {
      a.create_IOT_device(t.globalData.wx_openid);
      var l = setInterval((function () {
        "" != a.data.mqtt_payload_msg && (clearInterval(l), a.conect_aliyun_mqtt(a.data.mqtt_payload_msg))
      }), 200)
    }
  },
  conect_aliyun_mqtt: function (a) {
    var o = this,
      n = "wxs://" + c.getAliyunIotMqttClient({
        productKey: o.data.aliyunInfo.productKey,
        deviceName: o.data.aliyunInfo.deviceName,
        deviceSecret: o.data.aliyunInfo.deviceSecret,
        regionId: o.data.aliyunInfo.regionId,
        port: o.data.aliyunInfo.port
      }).host,
      l = a.deviceName,
      i = l + "&" + t.globalData.productKey,
      s = (t.globalData.productKey, a.clientId + "|securemode=2,authType=connwl|");
    console.log(s), console.log(t.globalData.productSecret), o.setData({
      "options.clientId": s,
      "options.password": a.deviceToken,
      "options.username": i
    }), console.log("this.data.options host:" + n), console.log("this.data.options data:" + JSON.stringify(o.data.options)), t.globalData.client = e.default.connect(n, o.data.options), t.globalData.client.on("connect", (function (e) {
      o.data.mqtt_conect_flag = !0;
      var a = "/" + t.globalData.productKey + "/" + t.globalData.wx_openid + "/user/get";
      t.globalData.client.subscribe(a, (function (e, t) {}))
    })), t.globalData.client.on("message", (function (e, a) {
      console.log(" 收到 topic:" + e + " , payload :" + a), e == "/" + t.globalData.productKey + "/" + t.globalData.wx_openid + "/user/get" && ("55" == a ? t.globalData.mqtt_tx_enable = !0 : "aa" == a && (t.globalData.mqtt_tx_enable = !1))
    })), t.globalData.client.on("error", (function (e) {
      o.data.mqtt_conect_flag = !1, console.log(" 服务器 error 的回调" + e)
    })), t.globalData.client.on("reconnect", (function () {
      o.data.mqtt_conect_flag = !1, console.log(" 服务器 reconnect的回调")
    })), t.globalData.client.on("offline", (function (e) {
      o.data.mqtt_conect_flag = !1, console.log(" 服务器offline的回调")
    }))
  },
  create_IOT_device: function (a) {
    var o = this,
      l = "wxs://" + c.getAliyunIotMqttClient({
        productKey: o.data.aliyunInfo.productKey,
        deviceName: o.data.aliyunInfo.deviceName,
        deviceSecret: o.data.aliyunInfo.deviceSecret,
        regionId: o.data.aliyunInfo.regionId,
        port: o.data.aliyunInfo.port
      }).host,
      i = a,
      s = i + "&" + t.globalData.productKey,
      r = "deviceName" + i + "productKey" + t.globalData.productKey + "random123";
    console.log(r);
    var d = "n1o38FYMlOnH4OZw6vbe000100|securemode=-2,authType=regnwl,random=123,signmethod=hmacsha1|";
    console.log(d), console.log(t.globalData.productSecret), o.setData({
      "options.clientId": d,
      "options.password": n.hex_hmac_sha1(t.globalData.productSecret, r),
      "options.username": s
    }), console.log("this.data.options host:" + l), console.log("this.data.options data:" + JSON.stringify(o.data.options)), t.globalData.client = e.default.connect(l, o.data.options), t.globalData.client.on("connect", (function (e) {
      wx.showToast({
        title: "连接成功"
      })
    })), t.globalData.client.on("message", (function (e, a) {
      console.log(" 收到 topic:" + e + " , payload :" + a);
      var n = String.fromCharCode.apply(null, a),
        c = JSON.parse(n);
      console.log(c), "/ext/regnwl" == e && "" != n && (wx.setStorageSync("mqtt_payload_msg", n), o.data.mqtt_payload_msg = c), t.globalData.client.end()
    })), t.globalData.client.on("error", (function (e) {
      console.log(" 服务器 error 的回调" + e)
    })), t.globalData.client.on("reconnect", (function () {
      console.log(" 服务器 reconnect的回调")
    })), t.globalData.client.on("offline", (function (e) {
      console.log(" 服务器offline的回调")
    }))
  },
  onShow: function () {},
  onReady: function () {},
  onUnload: function () {
    console.log("生命周期函数--监听页面卸载"), this.closeBluetoothAdapter()
  },
  backPage: function () {},
  fork_debug_mode: function (e) {
    0 == e.detail.value.length ? this.setData({
      fork_select_flag: !1
    }) : this.setData({
      fork_select_flag: !0
    }), t.globalData.fork_select_flag = this.data.fork_select_flag, 0 != this.data.fork_select_flag ? wx.setStorageSync("fork_moden_select_flag", "true") : wx.setStorageSync("fork_moden_select_flag", "false")
  },
  startClear: function () {
    this.setData({
      textLog: ""
    }), t.globalData.Storage_deviceId = wx.getStorageSync("deviceId"), 0 == t.globalData.fork_select_flag ? wx.navigateTo({
      url: "/pages/param_config/param_config"
    }) : wx.navigateTo({
      url: "/pages/fork_param_config/fork_param_config"
    })
  },
  startScan: function () {
    this._discoveryStarted = !1, this.data.isopen ? this.getBluetoothAdapterState() : this.openBluetoothAdapter()
  },
  openBluetoothAdapter: function () {
    var e = this;
    wx.openBluetoothAdapter({
      success: function (t) {
        var a = e.data.textLog + "打开蓝牙适配器成功！\n";
        e.setData({
          textLog: a,
          isopen: !0
        }), e.getBluetoothAdapterState()
      },
      fail: function (t) {
        var a = e.data.textLog + "蓝牙开关未开启 \n";
        e.setData({
          textLog: a
        })
      }
    }), wx.onBluetoothAdapterStateChange((function (t) {
      console.log("onBluetoothAdapterStateChange", t), t.available ? e.getBluetoothAdapterState() : (e.stopBluetoothDevicesDiscovery(), e.setData({
        devices: []
      }))
    }))
  },
  closeBluetoothAdapter: function () {
    wx.closeBluetoothAdapter({
      success: function (e) {
        console.log(e)
      }
    }), this._discoveryStarted = !1
  },
  getBluetoothAdapterState: function () {
    var e = this;
    wx.getBluetoothAdapterState({
      success: function (t) {
        var a = t.discovering;
        if (t.available) {
          var o = e.data.textLog + "本机蓝牙适配器状态：可用 \n";
          if (e.setData({
              textLog: o
            }), a) {
            o = e.data.textLog + "已在搜索设备 \n";
            e.setData({
              textLog: o
            })
          } else e.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  startBluetoothDevicesDiscovery: function () {
    var e = this;
    if (!e._discoveryStarted) {
      e._discoveryStarted = !0, t.showLoading("正在扫描..");
      var a = e.data.textLog + "正在扫描..\n";
      e.setData({
        textLog: a
      }), setTimeout((function () {
        wx.hideLoading()
      }), 500), wx.startBluetoothDevicesDiscovery({
        services: [],
        allowDuplicatesKey: !0,
        success: function (t) {
          var a = e.data.textLog + "扫描附近的蓝牙外围设备成功，准备监听寻找新设备:" + t + "\n";
          e.setData({
            textLog: a
          }), e.onBluetoothDeviceFound()
        }
      })
    }
  },
  stopBluetoothDevicesDiscovery: function () {
    var e = this.data.textLog + "停止搜寻附近的蓝牙外围设备 \n";
    this.setData({
      textLog: e
    }), wx.stopBluetoothDevicesDiscovery()
  },
  onBluetoothDeviceFound: function () {
    var e = this;
    wx.onBluetoothDeviceFound((function (a) {
      t.globalData.Storage_deviceId == a.devices[0].deviceId && 1 == t.globalData.auto_conect ? (e.data.deviceId = a.devices[0].deviceId, e.createBLEConnection_auto(e.data.deviceId)) : a.devices.forEach((function (t) {
        if (t.name || t.localName) {
          var a = e.data.devices,
            o = function (e, t, a) {
              for (var o = 0; o < e.length; o++)
                if (e[o][t] === a) return o;
              return -1
            }(a, "deviceId", t.deviceId),
            n = {}; - 1 === o ? n["devices[".concat(a.length, "]")] = t : n["devices[".concat(o, "]")] = t, e.setData(n)
        }
      }))
    }))
  },
  createBLEConnection_auto: function (e) {
    var t = this;
    wx.createBLEConnection({
      deviceId: e,
      success: function (a) {
        wx.hideLoading();
        var o = t.data.textLog + "配对成功,获取服务..\n";
        t.setData({
          textLog: o,
          connected: !0
        }), wx.setBLEMTU({
          deviceId: e,
          mtu: 28,
          success: function (e) {
            console.log("success")
          },
          fail: function (e) {
            console.log("fail")
          },
          complete: function (a) {
            t.getBLEDeviceServices(e)
          }
        })
      },
      fail: function (e) {
        wx.hideLoading();
        var a = t.data.textLog + "连接失败，错误码：" + e.errCode + "\n";
        t.setData({
          textLog: a
        }), t.closeBLEConnection()
      }
    }), t.stopBluetoothDevicesDiscovery()
  },
  createBLEConnection: function (e) {
    for (var o = this, n = e.currentTarget.dataset, c = n.deviceId, l = n.name, i = 0; i < o.data.devices.length; i++)
      if (o.data.devices[i].name == l) {
        t.globalData.ble_ManufacturerData = a.ab2hex(o.data.devices[i].advertisData);
        break
      } console.log(t.globalData.ble_ManufacturerData);
    var s = o.data.textLog + "正在连接，请稍后..\n";
    o.setData({
      textLog: s
    }), t.showLoading("连接中.."), wx.createBLEConnection({
      deviceId: c,
      success: function (e) {
        wx.hideLoading();
        var t = o.data.textLog + "配对成功,获取服务..\n";
        o.setData({
          textLog: t,
          connected: !0,
          name: l,
          devId: c
        }), wx.setBLEMTU({
          deviceId: c,
          mtu: 28,
          success: function (e) {
            console.log("success")
          },
          fail: function (e) {
            console.log("fail")
          },
          complete: function (e) {
            o.getBLEDeviceServices(c)
          }
        })
      },
      fail: function (e) {
        wx.hideLoading();
        var t = o.data.textLog + "连接失败，错误码：" + e.errCode + "\n";
        o.setData({
          textLog: t
        }), o.closeBLEConnection()
      }
    }), o.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection: function () {
    wx.closeBLEConnection({
      deviceId: this.data.devId
    }), this.setData({
      connected: !1,
      chs: [],
      canWrite: !1
    })
  },
  getBLEDeviceServices: function (e) {
    var a = this;
    wx.getBLEDeviceServices({
      deviceId: e,
      success: function (n) {
        for (var c = 0; c < n.services.length; c++)
          if (n.services[c].isPrimary && "0000FFE0-0000-1000-8000-00805F9B34FB" == n.services[c].uuid) {
            n.services[c].uuid;
            var l = a.data.textLog + "该服务是为主服务:" + n.services[c].uuid + "\n";
            a.setData({
              textLog: l
            }), t.globalData.ble_uuid = e, t.globalData.services_uuid = n.services[c].uuid, t.globalData.services_name = a.data.name;
            var i, s = wx.getStorageSync(t.globalData.ble_ManufacturerData);
            if (null == s && (s = ""), t.globalData.ble_ManufacturerData == s) console.log(t.globalData.ble_ManufacturerData), wx.navigateTo({
              url: "/pages/functionPage/functionPage"
            });
            else i = t.globalData.ble_ManufacturerData.length > 30 ? t.globalData.ble_ManufacturerData.substr(t.globalData.ble_ManufacturerData.length - 29, t.globalData.ble_ManufacturerData.length) : t.globalData.ble_ManufacturerData, o.request({
              Action: "QueryDeviceByTags",
              ProductKey: i,
              DeviceName: t.globalData.wx_openid,
              Tag: [{
                TagKey: t.globalData.ble_ManufacturerData,
                TagValue: t.globalData.ble_ManufacturerData
              }]
            }, {
              method: "POST"
            }, (function (e) {
              console.log(e.data), "" == e.data.Code && (0 != e.data.Total ? (console.log(e.data.Data.SimpleDeviceInfo[0]), console.log(e.data.Data.SimpleDeviceInfo[0].DeviceName), wx.setStorageSync(t.globalData.ble_ManufacturerData, t.globalData.ble_ManufacturerData), wx.navigateTo({
                url: "/pages/functionPage/functionPage"
              })) : wx.navigateTo({
                url: "/pages/functionPage/functionPage"
              }))
            }), (function (e) {
              console.log("fail"), wx.showToast({
                title: "网络连接失败",
                icon: "none",
                duration: 1e3,
                complete: function () {}
              })
            }), (function (e) {
              console.log("complete")
            }));
            return
          }
      }
    })
  }
});